package cn.edu.swu.auth;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebFilter(urlPatterns = {"/user/shopping", "/Pay.html"})
public class UserAuthenticationFilter implements Filter {

    public final static String LOGIN_TAG = "LOGIN_TAG";
    public final static String LOGIN_SUCCESS = "LOGIN_SUCCESS";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        Filter.super.init(filterConfig);
    }

    @Override
    public void destroy() {

        Filter.super.destroy();

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            HttpSession session = httpRequest.getSession(false);


            if (session == null || session.getAttribute(LOGIN_TAG) == null || !session.getAttribute(LOGIN_TAG).equals(LOGIN_SUCCESS)) {
                System.out.println("UserAuthenticationFilter: User not authenticated, redirecting to login page.");
                httpResponse.sendRedirect(httpRequest.getContextPath() + "/sign-in.html");
                return;
            } else {
                chain.doFilter(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();

            System.out.println("UserAuthenticationFilter: An error occurred: " + e.getMessage());
        }
    }

}
